package com.aw.puzzle.dropboxdiet;

import com.aw.puzzle.dropboxdiet.support.CombinationsLogger;

import java.util.Arrays;
import java.util.List;

/**
 * User: gmc
 * Date: 29/01/11
 */
public class CombinationSet extends AbstractActivityGroupProvider {
    private int id = 0;
    private int activitiesXGroup;
    private int numberOfGeneratedGroups = 0;
    private int[] lastCombination = null;
    private int[] lastCombinationOfPreviousCmbSet = null;
    private boolean atFirstReturnLastCombination = false;

    public CombinationSet(int id, List<Activity> activities, int activitiesXGroup) {
        super(activities);
        this.id = id;
        this.activitiesXGroup = activitiesXGroup;
    }

    public ActivityGroup getFirstGroup() {
        if (atFirstReturnLastCombination) {
            return getNewGroup(lastCombination);
        }
        return getNewGroup(getNextCombination());
    }

    public ActivityGroup getNextGroup() {
        return getNewGroup(getNextCombination());
    }

    private int[] getNextCombination() {
        if (id == 0 && numberOfGeneratedGroups == 0) {
            return combinationsGenerator.getFirstCombinationOfSize(activitiesXGroup);
        }
        return combinationsGenerator.getNextCombination(activities.size(), lastCombination);
    }


    private ActivityGroup getNewGroup(int[] newCombination) {
        if (newCombination != null && newCombination.length == activitiesXGroup) {
            CombinationsLogger.log("CombinationSet Elem", newCombination);
            ActivityGroup newGroup = getNewGroupBasedOn(newCombination);
            numberOfGeneratedGroups++;
            lastCombination = newCombination;
            return newGroup;
        }
        return null;
    }

    public boolean isFirst() {
        return id == 0;
    }

    public int getNumberOfGeneratedGroups() {
        return numberOfGeneratedGroups;
    }

    public void setPreviousCombinationSet(CombinationSet previousCombinationSet) {
        if (previousCombinationSet == null) {
            return;
        }
        lastCombinationOfPreviousCmbSet = previousCombinationSet.getLastCombination();
        this.lastCombination = Arrays.copyOf(lastCombinationOfPreviousCmbSet, lastCombinationOfPreviousCmbSet.length);
        this.lastCombination[activitiesXGroup - 1] = activities.size() - 1;
    }

    public int[] getLastCombination() {
        return lastCombination;
    }

    public int getId() {
        return id;
    }

    public int getActivitiesXGroup() {
        return activitiesXGroup;
    }

    public void setAtFirstReturnLastCombination() {
        this.atFirstReturnLastCombination = true;
    }
}

